package com.yufuchang;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * Created by yufuchang on 2020/9/7.
 */
@RestController
public class UploadController {

    @Autowired
    private RestTemplate restTemplate;
    @GetMapping("/upload_file")
    public void uploadFile(){
// 上传接口
        String url = "http://localhost:8080/upload_receive";
        // 待上传的文件
        String filePath = "F://Upload//test.txt";

        // 封装请求参数
        FileSystemResource resource = new FileSystemResource(new File(filePath));
        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
        param.add("myFile", resource);
        param.add("param1", "qew");
        param.add("param2", "qaefqw");

        // 发送请求并输出结果
        System.out.println("--- 上传文件 ---");
        String s = restTemplate.postForObject(url, param, String.class);
        System.out.println(s);
    }

    @PostMapping("/upload_receive")
    public String receiveUploadFile(String param1, String param2, MultipartFile myFile){
        System.out.println("--- 接收文件 ---");
        System.out.println("param1：" + param1);
        System.out.println("param2：" + param2);
        String originalFilename = myFile.getOriginalFilename();
        System.out.println("文件原始名称：" + originalFilename);
        try {
            String string = new String(myFile.getBytes(), "UTF-8");
            System.out.println("文件内容：" + string);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 处理文件内容...
        return "OK";
    }
}
